package ipl.projet.servlets;

import ipl.projet.domaine.Joueur;
import ipl.projet.usecase.UccStarTrek;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Connexion extends HttpServlet implements Servlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	private UccStarTrek ucc;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		/*
		if(request.getAttribute("erreur") != null) {
			System.out.println("coucou");
			String erreur = (String) request.getAttribute("erreur");
			request.setAttribute("erreur", erreur);
		}
		*/
		getServletContext().getNamedDispatcher("connexion.html").forward(
				request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		if(login == null || login == "") {
			request.setAttribute("erreur", "2");
			getServletContext().getNamedDispatcher("connexion.html").forward(
					request, response);
			return;
		}
		
		Joueur joueur = ucc.connexion(login);
		HttpSession session = request.getSession();
		if(joueur != null && session != null) {
			session.setAttribute("login", joueur.getLogin());
			response.sendRedirect(response.encodeRedirectURL("accueil.html"));
			return;
		}
	}
}
